package com.example.petmall.seckill.interceport;

import com.qianji.common.constant.AuthConstant;
import com.qianji.common.to.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liang zai
 * @date 2022/4/24 17:06
 * @description
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    //只要线程不切换就一直有效
    public static ThreadLocal<MemberResponseVo> thread_Local = new ThreadLocal<>();
    //请求之前进行调用拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);

        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match(requestURI, "/addSeckillCart");
        if (!match){
            return true;
        }
        if (attribute!=null){
            thread_Local.set(attribute);
            return true;
        }else {
            //用户没登录,去登录
            request.getSession().setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.petmall.com/login.html");
            return false;
        }
    }
}
